using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 长按事件组件，可挂载到GameObject上处理长按逻辑
    /// </summary>
    public class LongPressEventComponent : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
    {
        [Tooltip("长按触发时间（秒）")]
        public float duration = 1.0f;
        
        [Tooltip("是否只触发一次")]
        public bool triggerOnce = false;
        
        public UnityEvent OnLongPress;
        
        private Coroutine m_LongPressCoroutine;
        private bool m_IsPressed;
        private bool m_HasTriggered;
        
        public void OnPointerDown(PointerEventData eventData)
        {
            if (triggerOnce && m_HasTriggered)
                return;
                
            m_IsPressed = true;
            m_HasTriggered = false;
            
            if (m_LongPressCoroutine != null)
                StopCoroutine(m_LongPressCoroutine);
                
            m_LongPressCoroutine = StartCoroutine(LongPressCoroutine());
        }
        
        public void OnPointerUp(PointerEventData eventData)
        {
            m_IsPressed = false;
            
            if (m_LongPressCoroutine != null)
            {
                StopCoroutine(m_LongPressCoroutine);
                m_LongPressCoroutine = null;
            }
        }
        
        public void OnPointerExit(PointerEventData eventData)
        {
            m_IsPressed = false;
            
            if (m_LongPressCoroutine != null)
            {
                StopCoroutine(m_LongPressCoroutine);
                m_LongPressCoroutine = null;
            }
        }
        
        private IEnumerator LongPressCoroutine()
        {
            float startTime = Time.time;
            while (m_IsPressed && (Time.time - startTime) < duration)
            {
                yield return null;
            }
            
            if (m_IsPressed && (Time.time - startTime) >= duration)
            {
                m_HasTriggered = true;
                OnLongPress?.Invoke();
            }
            
            m_LongPressCoroutine = null;
        }
        
        private void OnDisable()
        {
            if (m_LongPressCoroutine != null)
            {
                StopCoroutine(m_LongPressCoroutine);
                m_LongPressCoroutine = null;
            }
            
            m_IsPressed = false;
            m_HasTriggered = false;
        }
        
        /// <summary>
        /// 移除所有事件监听器
        /// </summary>
        public void RemoveAllListeners()
        {
            OnLongPress?.RemoveAllListeners();
        }
        
        private void OnDestroy()
        {
            OnDisable();
            RemoveAllListeners();
        }
    }
}